<?php

declare(strict_types=1);

namespace App\Model;

use App\Cache\RedisKey;
use App\Helpers\ImUtil;
use App\Helpers\RedisUtil;
use Hyperf\DbConnection\Model\Model;
use Hyperf\DbConnection\Db;

/**
 * 聊天记录
 */
class UserMsgLog extends Model
{
    protected $table = 'user_msg_log';
    protected $fillable = [
        'msg_type', 'from_userid', 'to_userid', 'from_account', 'to_account', 'msg_detail', 'flag', 'official'
    ];

    /**
     * 关联用户
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    function fromUser()
    {
        return $this->belongsTo(UserProfile::class, 'from_userid', 'user_id');
    }

    /**
     * 关联聊天对象
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    function toUser()
    {
        return $this->belongsTo(UserProfile::class, 'to_userid', 'user_id');
    }

    /**
     * 查询发送的消息记录数
     */
    static function getSendMsgNum($userId = 0, $chatUserId = 0, $startTime = '')
    {
        $where = [
            ['from_userid', $userId],
        ];
        if ($chatUserId) $where[] = ['to_userid', $chatUserId];
        if ($startTime) $where[] = ['created_at', '>=', $startTime];
        return self::where($where)->count();
    }

    /**
     * 获取官方列表列表
     * @return mixed
     */
    static function getOfficialList($num = 1000, $accounts = [])
    {
        $where = [
            'flag' => 1,
            'official' => 1,
        ];
        if (empty($accounts)) {
            return self::where($where)->orderBy('id', 'desc')->limit($num)->get();
        } else {
            return self::where($where)->whereIn('from_userid', $accounts)->orWhere(function ($query) use ($where, $accounts) {
                $query->where($where)->whereIn('to_userid', $accounts);
            })->orderBy('id', 'desc')->limit($num)->get();
        }
    }

    /**
     * 封装融云消息详情
     * @param array $msgDetail
     * @param int $msgId
     */
    static function packMsgDetail($msgDetail = [], $msgId = 0)
    {
        $obj = ['MsgType' => $msgDetail['objectName']];
        switch ($msgDetail['objectName']) {
            case ImUtil::RONG_TEXT_TYPE:
                $obj['MsgContent']['Text'] = $msgDetail['content']['content'];
                break;
            case ImUtil::RONG_IMG_TYPE:
                $obj['MsgContent']['Text'] = "【图片消息：{$msgId}】";
                $obj['MsgContent']['ImgUrl'] = $msgDetail['content']['imageUri'];
                break;
            case ImUtil::RONG_SOUND_TYPE:
                $obj['MsgContent']['Text'] = "【语音消息：{$msgId}】";
                break;
            case ImUtil::MSG_TYPE_GIFT:
                $obj['MsgContent']['Text'] = "【礼物消息：{$msgId}】";
                break;
            default:
                $obj['MsgContent']['Text'] = "【未知消息：Type：{$msgDetail['objectName']}；ID：{$msgId}】";
                break;
        }
        return $obj;
    }

    /**
     * 收费开始的发送消息数
     */
    static function checkChargeBeginNum($userId = 0, $chatUserId = 0, $deviceId = '', $maxLmt = 10)
    {
        $cacheKey1 = "msg_num_check_charge_{$userId}";
        $cacheKey2 = "msg_num_check_charge_{$deviceId}";
        if (
            RedisUtil::get($cacheKey1) == 1
            // (!check_dev_env() && RedisUtil::get($cacheKey2) == 1)
        ) return false;

        $key = RedisKey::getUserMsgNum($userId);
        $redis = RedisUtil::getRedis();


        $ctn = $redis->zScore($key,0);
        $where = [
            ['from_userid', $userId],
        ];
        if (empty($ctn)){
            $ctn = self::where($where)->count();
        }

        if ($ctn < $maxLmt) {
            //单人消息5条的

            $singleCtn = $redis->zScore($key,$chatUserId);
            if (empty($singleCtn)){
                $where[] = ['to_userid', $chatUserId];
                $singleCtn = self::where($where)->count();
            }

            $singleMax = env('CHAT_FREE_SINGLE_MAX_NUM', 5);
            if ($singleCtn < $singleMax) {
                return true;
            }
            log_info(__METHOD__ . "=={$userId}==Less==Msgnum:{$ctn}:maxLmt:{$maxLmt}");
            return false;
        } else {
            //加入限制记录
            UserPassChatlmt::addRecord($userId, $deviceId, $ctn);
            log_info(__METHOD__ . "=={$userId}==More==Msgnum:{$ctn}:maxLmt:{$maxLmt}");
            $cacheTime = 3600 * 72;
            RedisUtil::set($cacheKey1, 1, $cacheTime);
            // $deviceId && RedisUtil::set($cacheKey2, 1, $cacheTime);
            return false;
        }
    }

    /**
     * 判断是否新人优惠
     * @param int $userId
     * @param int $chatUserId
     * @param int $maxLmt
     * @return bool
     */
    public static function getByUidCount($userId = 0,$chatUserId = 0,$maxLmt=10)
    {
        $where = [
            ['from_userid', $userId],
        ];
        $ctn = self::where($where)->count();
        if ($ctn < $maxLmt){
            $where[] = ['to_userid', $chatUserId];
            $singleCtn = self::where($where)->count();
            if ($singleCtn < env('CHAT_FREE_SINGLE_MAX_NUM', 5)) {
                return true;
            }
            return false;
        }
        return false;
    }
}
